package com.lgqz.himalayafm.fragment;


import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.lgqz.himalayafm.DrawListener;
import com.lgqz.himalayafm.R;
import com.lgqz.himalayafm.adapter.CategoriesAdapter;
import com.lgqz.himalayafm.adapter.CategoriesViewPagerAdapter;
import com.lgqz.himalayafm.bean.CataIndexBannerEntity;
import com.lgqz.himalayafm.bean.CategoriesEntity;
import com.lgqz.himalayafm.bean.CategoriseListData;
import com.lgqz.himalayafm.http.HttpService;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * A simple {@link Fragment} subclass.
 */
public class CategoriesFragment extends Fragment implements Callback<CategoriesEntity>, ViewPager.OnPageChangeListener {

    private int pagePosition = 0;
    private List<ImageView> pointList;
    private int[] pointIds = new int[]{R.id.categories_viewpager_point1_iv, R.id.categories_viewpager_point2_iv, R.id.categories_viewpager_point3_iv,};
    private CategoriesAdapter adapter;
    private SimpleDraweeView simpleDraweeView;
    private ViewPager viewPager;
    private List<CategoriseListData> list;
    private Timer timer;
    private TimerTask task;
    private int WHAT_KEY = 1;
    private List<SimpleDraweeView> simpleDraweeViews;
    private DrawListener drawListener;

    public CategoriesFragment() {
        // Required empty public constructor

    }

    private Handler recycleHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        //初始化viewpager的小圆点
        //下载recyclerview数据
        drawListener = (DrawListener) getActivity();
        initData();
        View view = inflater.inflate(R.layout.fragment_categories, container, false);
        //初始化viewpager的小圆点

        RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.categories_recycler);
        simpleDraweeView = (SimpleDraweeView) view.findViewById(R.id.categories_simpledraweeview);
        simpleDraweeView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getContext(),"nihao",Toast.LENGTH_LONG).show();
                //Log.d("1620", "onClick: opendraw1");
                drawListener.openDraw(null,null);
                //Log.d("1620", "onClick: opendraw2");
            }
        });
        viewPager = (ViewPager) view.findViewById(R.id.categories_viewpager);
        pointList = new ArrayList<>();
        for (int i = 0; i < pointIds.length; i++) {
            ImageView pointImageView = (ImageView) view.findViewById(pointIds[i]);
            pointList.add(pointImageView);
        }
        pointList.get(0).setSelected(false);
        //下载viewpager数据
        initViewPagerData();
        GridLayoutManager manager = new GridLayoutManager(getContext(), 2);
        adapter = new CategoriesAdapter(getContext());
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(manager);
        RecyclerView.ItemDecoration decoration = new RecyclerView.ItemDecoration() {
            @Override
            public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
                super.onDraw(c, parent, state);
            }

            @Override
            public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
                super.onDrawOver(c, parent, state);
            }

            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                int position = parent.getChildAdapterPosition(view);
                int margin;
                if ((position + 1) % 6 == 0) {
                    margin = 10;
                    outRect.set(0, 0, 0, margin);
                }
            }
        };
        recyclerView.addItemDecoration(decoration);
        return view;
    }

    private void initViewPagerData() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://adse.ximalaya.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        //    http://adse.ximalaya.com/ting?device=android&name=cata_index_banner
        //    &network=wifi&operator=0&version=4.3.98
        HttpService service = retrofit.create(HttpService.class);
        service.getCataIndexBannerData("android", "cata_index_banner", "wifi", 0, "4.3.98").enqueue(new Callback<CataIndexBannerEntity>() {
            @Override
            public void onResponse(Call<CataIndexBannerEntity> call, Response<CataIndexBannerEntity> response) {
                CataIndexBannerEntity cataIndexBannerEntity = response.body();
                simpleDraweeViews = new ArrayList<SimpleDraweeView>();
                for (int i = 0; i < cataIndexBannerEntity.getData().size(); i++) {
                    SimpleDraweeView simpleDraweeView = new SimpleDraweeView(getContext());
                    simpleDraweeView.setImageURI(cataIndexBannerEntity.getData().get(i).getCover());
                    simpleDraweeViews.add(simpleDraweeView);
                }
                SimpleDraweeView simpleDraweeView = new SimpleDraweeView(getContext());
                simpleDraweeView.setImageURI(cataIndexBannerEntity.getData().get(0).getCover());
                simpleDraweeViews.add(simpleDraweeView);
                Log.d("1620", "onResponse: " + simpleDraweeViews.size());
                CategoriesViewPagerAdapter categoriesViewPagerAdapter = new CategoriesViewPagerAdapter(simpleDraweeViews);
                viewPager.setAdapter(categoriesViewPagerAdapter);
                viewPager.addOnPageChangeListener(CategoriesFragment.this);
                viewPager.setCurrentItem(0, false);
                recyclePlay();

            }

            @Override
            public void onFailure(Call<CataIndexBannerEntity> call, Throwable t) {

            }
        });
    }

    private void recyclePlay() {
        if (timer != null) {
            timer.cancel();
        }
        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                recycleHandler.sendEmptyMessage(WHAT_KEY);
            }
        };
        timer.schedule(task, 1000, 3000);
    }


    private void initData() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://mobile.ximalaya.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        HttpService service = retrofit.create(HttpService.class);
        service.getCategoriesData("v1", "categories", "and-a1", "android", 13, 2).enqueue(this);
    }

    @Override
    public void onResponse(Call<CategoriesEntity> call, Response<CategoriesEntity> response) {
        CategoriesEntity categoriesEntity = response.body();
        List<CategoriseListData> categoriseListDatas = categoriesEntity.getList();
        list = new ArrayList<>();
        simpleDraweeView.setImageURI(categoriseListDatas.get(0).getCoverPath());
        for (int i = 1; i < categoriseListDatas.size(); i++) {
            list.add(categoriseListDatas.get(i));
        }
        adapter.addAll(list);
    }

    @Override
    public void onFailure(Call<CategoriesEntity> call, Throwable t) {
        t.printStackTrace();
        Log.d("1620", "onFailure: " + t.getMessage());
    }

    @Override
    public void onPageScrolled(int position, float positionOffset,
                               int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        pagePosition = position;
        for (int i = 0; i < pointList.size(); i++) {
            pointList.get(i).setSelected(i == position);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        switch (state) {
            case ViewPager.SCROLL_STATE_IDLE:
                if (pagePosition == simpleDraweeViews.size() - 1) {
                    viewPager.setCurrentItem(0, false);
                }
                break;
            case ViewPager.SCROLL_STATE_DRAGGING:

                break;
            case ViewPager.SCROLL_STATE_SETTLING:

                break;
        }

    }

    @Override
    public void onDetach() {
        super.onDetach();
        viewPager.removeOnPageChangeListener(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        viewPager.removeOnPageChangeListener(this);
    }

//    public void clickBtn(View view) {
//        switch (view.getId()) {
//            case R.id.categories_simpledraweeview:
//                drawListener.openDraw();
//                break;
//        }
//    }

}
